package com.vanzo.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.vanzo.Configure;
import com.vanzo.util.LogUtil;

/**
 * Created by tisen on 2018/2/24.
 */

public class PttKeyReceiver extends BroadcastReceiver {

    public static final String ACTION_PTT_UP = "con.vanzo.talkie.ptt.up";
    public static final String ACTION_PTT_DOWN = "con.vanzo.talkie.ptt.down";
    private Talkie talkie;
    private boolean isTimeOut = false;
    private OnKeyListener listener;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (talkie == null) {
            talkie = new Talkie(context);
        }
        if (!talkie.isBind()) {
            talkie.bind();
        }
        if (intent.getAction().equals(ACTION_PTT_UP)) {
            LogUtil.put(this, ACTION_PTT_UP, LogUtil.WARN);
            if (isTimeOut) {
                isTimeOut = false;
            } else {
                talkie.sendPttUp();
                listener.onKeyListener(ACTION_PTT_UP);
                pttDownTimeOut.removeMessages(0);
            }
        } else if (intent.getAction().equals(ACTION_PTT_DOWN)) {
            LogUtil.put(this, ACTION_PTT_DOWN, LogUtil.WARN);
            talkie.sendPttDown();
            listener.onKeyListener(ACTION_PTT_DOWN);
            pttDownTimeOut.sendEmptyMessageDelayed(0, Configure.PTT_TIME_OUT);
        }
    }

    private Handler pttDownTimeOut = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isTimeOut = true;
            talkie.sendPttUp();
            listener.onKeyListener(ACTION_PTT_UP);
        }
    };

    public void unbind() {
        if (talkie != null)
            talkie.unbind();
    }

    public void setListener(OnKeyListener listener) {
        this.listener = listener;
    }

    public interface OnKeyListener{
        void onKeyListener(String action);
    }
}
